<?php
/**
 * Created by PhpStorm.
 * User: xsp
 * Date: 2018/4/15
 * Time: 20:32
 */

namespace frontend\controllers;


use backend\models\Product;
use common\models\User;
use frontend\models\Address;
use frontend\models\Cart;
use frontend\models\Order;
use frontend\models\OrderDetail;

use yii\filters\AccessControl;
use yii\web\Controller;

class OrderController extends CommonController
{
protected $mustLogin = ['*'];

    public function actionIndex()
    {
        $this->layout = 'layout2';
//        $id = \Yii::$app->session['user']['uid'];
//        $orders = Order::find()->where(['userid' => $id])->join('LEFT JOIN', 'shop_product', 'shop_order.orderid')->all();
////        var_dump($orders);die;
//        return $this->render('index', ['orders' => $orders]);

        return $this->render('index');
    }

    /**
     * 收银台界面
     * @return string
     */
    public function actionCheck()
    {
        if (\Yii::$app->user->isGuest) {
            return $this->redirect(['member/auth']);
        }
        $uid = \Yii::$app->user->id;

        $session = \Yii::$app->session;
        if (empty($session['user'])) {
            return $this->redirect(['member/auth']);
        }
        $uid = \Yii::$app->session['user']['uid'];
        $orderid = \Yii::$app->request->get('orderid');
        $status = Order::find()->where(['orderid' => $orderid])->one()->status;
        if ($status != Order::CREATEORDER && $status != Order::CHECKORDER) {
            return $this->redirect(['order/index']);
        }
        $address = Address::find()->where(['userid' => $uid])->asArray()->all();
        $details = OrderDetail::find()->where(['orderid' => $orderid])->asArray()->all();
        $data = [];
        foreach ($details as $detail) {
            $model = Product::find()->where(['productid' => $detail['productid']])->one();

            $detail['title'] = $model->title;
            $detail['cover'] = $model->cover;
            $data[] = $detail;
        }
        $express = \Yii::$app->params['express'];
        $expressPrice = \Yii::$app->params['expressPrice'];
        $this->layout = "layout1";
        return $this->render("check", ['express' => $express, 'expressPrice' => $expressPrice, 'addresses' => $address, 'products' => $data]);
    }

    /*
     * 订单添加功能
     */
    public function actionAdd()
    {
        $session = \Yii::$app->session;
        if (empty($session['user'])) {
            return $this->redirect(['member/auth']);
        }
        $tran = \Yii::$app->db->beginTransaction();
        try {
            if (\Yii::$app->request->isPost) {
                $post = \Yii::$app->request->post();
                $user = User::find()->where(['userid' => $session['user']['uid']])->one();

                if (!$user) {
                    throw new \Exception();
                }
                $order = new Order();
                $order->userid = $session['user']['uid'];
                $order->createtime = time();
                $order->status = Order::CREATEORDER;

                if (!$order->save()) {
                    throw new \Exception();
                }
                $orderid = $order->getPrimaryKey();

                foreach ($post['OrderDetail'] as $product) {
                    $model = new OrderDetail;
                    $product['orderid'] = $orderid;
                    $product['createtime'] = time();
                    $data['OrderDetail'] = $product;
                    if (!$model->add($data)) {
                        throw new \Exception();
                    }
                    Cart::deleteAll(['productid' => $product['productid']]);
                    Product::updateAllCounters(['num' => -$product['productnum']], ['productid' => $product['productid']]);//更新符合条件的所有计数列

                }
            }
            $tran->commit();
        } catch (\Exception $e) {
            $tran->rollBack();
            return $this->redirect(['cart/index']);
        }
        return $this->redirect(['order/check', 'orderid' => $orderid]);
    }

    /**
     * 确认订单
     */
    public function actionConfirm()
    {
        try {
            if (!\Yii::$app->session['user']) {
                return $this->redirect(['member/login']);
            }
            $post = \Yii::$app->request->post();
            $uid = \Yii::$app->session['user']['uid'];
            $order = Order::find()->where(['orderid' => $post['orderid'], 'userid' => $uid])->all();
            if (!$order) {
                throw new \Exception();
            }
            $detail = OrderDetail::find()->where(['orderid' => $post['orderid']])->all();
            $amount = 0;
            foreach ($detail as $value) {
                $amount += $value['productnum'] * $value['price'];
            }
            $post['status'] = Order::CHECKORDER;
            if ($amount <= 0) {
                throw new \Exception();
            }
            $express = \Yii::$app->params['expressPrice'][$post['expressid']];
            $amount += $express;
            $post['amount'] = $amount;
            $data[] = $post;
            if ($order->load($data) && $order->save()) {
                return $this->redirect(['order/pay', 'orderid' => $post['orderid'], 'paymethod' => $post['paymethod']]);
            }
        } catch (\Exception $e) {
            return $this->redirect(['index/index']);
        }
    }
}